const CheckAuth = require("../../util/auth")
const request = require("../../util/request")

// pages/shopcar/shopcar.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    slideButtons: [{
      type: 'warn',
      text: '删除'
    }],
    cartList: [],
    checked: false
  },
  sildeButtonTap(evt) {
    let id =evt.currentTarget.dataset.id
    this.delete(id)
  },
  handleCheck(evt) {
    let item = evt.currentTarget.dataset.item
    item.checked = !item.checked
    this.handleUpdate(item)
  },

  handleMinus(evt) {
    let item = evt.currentTarget.dataset.item
    if (item.number > 1) {
      item.number = --item.number
      this.handleUpdate(item)
    } else {
      this.delete(item.id)
    }
  },
  delete(id) {
    request({
      url: `/carts/${id}`,
      method: "delete"
    })
    this.getCartList()
  },
  handleAdd(evt) {
    let item = evt.currentTarget.dataset.item
    item.number = ++item.number
    this.handleUpdate(item)
  },
  handleUpdate(item) {
    this.setData({
      cartList: this.data.cartList.map(data => {
        if (data.id === item.id) {
          return item
        } else {
          return data
        }
      })
    })
    request({
      url: `/carts/${item.id}`,
      method: "put",
      data: {
        "checked": item.checked,
        "goodId": item.goodId,
        "id": item.id,
        "number": item.number,
        "tel": item.tel,
        "username": item.username,
      },
    })
  },
  handleSelectAll() {
    this.setData({
      checked: !this.data.checked
    })
    this.data.cartList.map(data => {
      data.checked = this.data.checked
      this.handleUpdate(data)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    CheckAuth(() => {
      this.getCartList()
    })
  },

  getCartList() {
    let username = wx.getStorageSync('token').nickName
    let tel = wx.getStorageSync('tel')
    request({
      url: `/carts?_expand=good&username=${username}&tel=${tel}`
    }).then(res => {
      this.setData({
        cartList: res
      })
      res.map(item => {
        if (item.checked) {
          this.setData({
            checked: true
          })
        } else {
          this.setData({
            checked: false
          })
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})